package com.ruike.alisurface.ui.setting;

import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.AppInfoBean;
import com.ruike.alisurface.http.AppUpdateHttp;
import com.ruike.alisurface.services.AppRunMonitoringService;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.utils.APPUtils;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.voodoo.lib_frame.httpTools.DownloadUtil;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: voodoo
 * CreateDate: 2020/08/18 018 10:11 上午
 * Description: 守护程序操作
 */
public class AppDaemonActivity extends BaseAty {

    @BindView(R.id.appDemonSetting_showStatus_llayout)
    LinearLayout showStatusLlayout;
    @BindView(R.id.appDemonSetting_showStatus_tv)
    TextView showStatusTv;
    @BindView(R.id.appDemonSetting_progress_pb)
    ProgressBar progressPb;

    private String downloadPath = Environment.getExternalStorageDirectory().getPath();
    private String downloadFileName = "tempAppDemonApp.apk";

    private boolean isUninstallClick = false;
    private String daemonAppPackage = "com.voodoo.appdaemon";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_setting_app_demon;
    }

    @Override
    protected void initViews() {
        initTitleBar(false);

    }

    @Override
    protected void initData() {
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = new Intent("com.MainApp.Action.Start"); // 发送主程序启动的广播
        sendBroadcast(intent);
    }

    @OnClick({R.id.appDemonSetting_goback_imgv, R.id.appDemonSetting_openDemon_btn, R.id.appDemonSetting_downloadMainApp_btn, R.id.appDemonSetting_downloadApp_btn})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.appDemonSetting_goback_imgv:
                finish();
                break;
            case R.id.appDemonSetting_openDemon_btn: // 打开守护程序
                // //////////////////////////////////// 此处修改 ////////////////////////////////////
                showProgressDialog("正在获取最新守护程序，请稍后...");
                AppUpdateHttp.getAppVersion("SH", this);
                ////////////////////////////////////////////////////////////////////////////////////
                break;
            case R.id.appDemonSetting_downloadMainApp_btn: // 下载安装主程序 pm uninstall com.ruike.alisurface
                uninstallMainApp();
                break;
            case R.id.appDemonSetting_downloadApp_btn: //
                // 停止服务退出APP
                // 点击的时候发送一条广播出去
                Intent intent = new Intent("com.MainApp.Action.Exit"); // 发送APP退出的广播
                sendBroadcast(intent);
                stopService(new Intent(this, AppRunMonitoringService.class));
                Intent intent1 = new Intent(Settings.ACTION_DISPLAY_SETTINGS);
                startActivity(intent1);
                break;
        }
    }

    /**
     * 卸载主程序，让守护程序去下载最新版的主程序安装并且打开
     */
    private void uninstallMainApp() {
        if (!isUninstallClick) {

            boolean appInstalled = APPUtils.isAppInstalled(this, daemonAppPackage);
            if (appInstalled) {
                if (APPUtils.isAppRunning(this, daemonAppPackage)) {
                    isUninstallClick = true;
                    showProgressDialog("正在卸载主程序，请稍等...");
                    new MyCountDownTimer(2000, 2000) {

                        @Override
                        public void onTick(long millisUntilFinished) {

                        }

                        @Override
                        public void onFinish() {
                            // ////////////////////////////// 此处修改 //////////////////////////////
                            // 直接卸载本APP
                            APPUtils.uninstallApk(BuildConfig.APPLICATION_ID);
                            ////////////////////////////////////////////////////////////////////////
                        }
                    }.start();
                } else {
                    showErrorTip("守护程序未运行，请先打开守护程序...");
                }
            } else {
                L.i("tag_请先安装守护程序");
                showErrorTip("请先安装守护程序...");
            }
        }
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);

        if (requestUrl.endsWith("Get_AppVersion")) {

            AppInfoBean appInfoBean = GsonUtils.json2Model(requestJsonStr, AppInfoBean.class);
            if (appInfoBean.getData().getDownloadUrl().isEmpty()) {
                return;
            }

            if (appInfoBean.getData().getAppProject_id().equals("SH")) {

                // //////////////////////////////////// 此处修改 ////////////////////////////////////

                boolean appInstalled = APPUtils.isAppInstalled(this, daemonAppPackage);
                if (appInstalled) {

                    // 当前安装的守护程序版本号
                    String appdaemonApkPath = APPUtils.getApkPath(this, daemonAppPackage);
                    int apkVersionCode = APPUtils.getApkVersionCode(this, appdaemonApkPath);

                    // 后台回传的守护程序版本号（后台记录的是版本名称，守护程序版本号和版本名称是统一的，例如：版本号：20201027 版本名称：2020.10.27）
                    String versionStr = appInfoBean.getData().getVersion().replace(".", "");
                    int version = Integer.parseInt(versionStr);

                    // 判断本地Apk的VersionCode是否小于后台回传的VersionCode
                    if (apkVersionCode < version) {
                        showDownloadDaemonApp("检测提示",
                                "当前守护程序版本较低，建议您尽快下载新程序",
                                "下载并安装",
                                "稍后下载",
                                appInfoBean.getData().getDownloadUrl());
                    } else { // 后台版本与本地版本一致或本地版本高于后台版本
                        if (APPUtils.isAppRunning(this, daemonAppPackage)) {
                            APPUtils.stopAppByKill(this, daemonAppPackage);
                        }
                        APPUtils.openPackage(this, daemonAppPackage);
                    }
                } else {
                    showDownloadDaemonApp("检测提示",
                            "守护程序未安装，是否下载安装守护程序，建议您尽快下载",
                            "下载并打开",
                            "稍后下载",
                            appInfoBean.getData().getDownloadUrl());
                }

                ////////////////////////////////////////////////////////////////////////////////////
            }
        }

    }

    // ////////////////////////////////////////// 此处修改 //////////////////////////////////////////
    /**
     * 展示下载守护程序的弹窗
     *
     * @param titleStr    展示标题
     * @param msg         展示消息
     * @param positiveStr 确认按钮文字
     * @param negativeStr 取消按钮文字
     * @param downloadUrl 下载地址
     */
    private void showDownloadDaemonApp(String titleStr, String msg, String positiveStr, String negativeStr, String downloadUrl) {
        new CustomDialog.Builder(this)
                .setTitle(titleStr)
                .setMessage(msg)
                .setTouchOutsideCloseDialog(false)
                .setPositiveButton(positiveStr, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 下载守护程序
                        boolean downloading = DownloadUtil.getInstance().isDownloading();
                        if (downloading) {
                            showErrorTip("有任务正在下载中，请稍等...");
                        } else {
                            DownloadUtil.getInstance().download(downloadUrl, downloadPath, downloadFileName, AppDaemonActivity.this);
                        }
                    }
                })
                .setNegativeButton(negativeStr, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .create().show();
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////

    @Override
    public void onFailure(String requestUrl, String requestMsg) {
        super.onFailure(requestUrl, requestMsg);
        showErrorTip(requestMsg);
    }

    @Override
    public void onDownloading(String requestUrl, long total, long progress) {
        super.onDownloading(requestUrl, total, progress);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (showStatusLlayout.getVisibility() == View.GONE) {
                    showStatusTv.setText("正在下载中...");
                    showStatusLlayout.setVisibility(View.VISIBLE);
                }
                progressPb.setProgress((int) progress);
            }
        });
    }

    @Override
    public void onDownloadSuccess(String requestUrl, File file) {
        super.onDownloadSuccess(requestUrl, file);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showStatusTv.setText("下载成功，正在安装..");
                boolean isInstalled = APPUtils.clientInstall(file.getPath());
                if (isInstalled) {
                    APPUtils.openPackage(AppDaemonActivity.this, daemonAppPackage);
                } else {
                    showStatusTv.setText("安装失败，请重新安装...");
                }
                showStatusTv.setVisibility(View.GONE);
                progressPb.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onDownloadFailed(String requestUrl, Exception e) {
        super.onDownloadFailed(requestUrl, e);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showStatusTv.setText("下载失败，请重试...");
                showErrorTip("下载失败，请重试...");
                L.e("下载守护程序失败", "url:" + requestUrl, e.toString());
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        showStatusTv.setVisibility(View.VISIBLE);
        showStatusTv.setText("启动成功");
    }
}
